package cn.ejiakanghu.logistics.service.impl;


import cn.com.ejiakanghu.core.config.DirectExchangeRabbitMQConfig;
import cn.com.ejiakanghu.core.enums.ResultCode;
import cn.com.ejiakanghu.core.exception.CheckException;
import cn.com.ejiakanghu.core.exceptions.BizException;
import cn.com.ejiakanghu.core.rabbitmq.DirectExchangeProducer;
import cn.ejiakanghu.logistics.service.LogisticBusiBaseService;
import cn.ejiakanghu.logistics.third.shunfeng.ShunfengCreateOrderBody;
import cn.ejiakanghu.logistics.third.shunfeng.ShunfengResponseData;
import cn.ejiakanghu.logistics.third.shunfeng.ShunfengResposeCreateOrder;
import cn.ejiakanghu.logistics.third.shunfeng.ThirdLogisticShunFengTool;
import cn.ejiakanghu.logistics.vo.StoreDeliveryModeEnum;
import cn.ejiakanghu.logistics.vo.WarehouseTypeEnum;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.inventory.InventoryService;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.db.dao.logistics.LogisticsMapper;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallShopMapper;
import org.linlinjava.litemall.db.domain.AgedmallLgReceiveOrder;
import org.linlinjava.litemall.db.service.AgedmallAnnouncerBaseInfoService;
import org.linlinjava.litemall.db.service.AgedmallLgMissionService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.oder_manage.AgedMallOrderDbService;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.locks.PickUp;
import org.linlinjava.litemall.db.vo.logistics.LogisticsBackUserAddressData;
import org.linlinjava.litemall.db.vo.logistics.LogisticsCommonData;
import org.linlinjava.litemall.db.vo.logistics.LogisticsGoodsTypeData;
import org.linlinjava.litemall.db.vo.shop.ChainLockPickup;
import org.linlinjava.litemall.db.vo.shop.MedicalLockPickup;
import org.linlinjava.litemall.db.vo.wechat.ToLitemallBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static org.linlinjava.litemall.db.util.OrderUtil.*;

/**
 * @author ：sujp
 * @date ：Created in 2021/11/5 15:13
 * @description：物流业务
 * @modified By：
 * @version: 1.0
 */
@Service
public class LogisticBusiBaseServiceImpl extends LogisticBusiBaseService {
    Logger logger = LoggerFactory.getLogger(LogisticBusiBaseServiceImpl.class);

    @Autowired
    private LogisticsBaseServiceAbstractImpl logisticsBaseServiceAbstractImpl;
    @Resource
    private DirectExchangeProducer directExchangeProducer;
    @Resource
    private AgedMallOrderDbService agedMallOrderDbService;
    @Resource
    private AgedmallLgMissionMapper agedmallLgMissionMapper;
    @Resource
    private AgedmallLgReceiveOrderMapper agedmallLgReceiveOrderMapper;
    @Resource
    private AgedmallLgBaseInfoMapper agedmallLgBaseInfoMapper;
    @Resource
    private AgedmallDeliveryManInfoMapper agedmallDeliveryManInfoMapper;
    @Resource
    private AgedmallLgBusiRecordMapper agedmallLgBusiRecordMapper;
    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;
    @Resource
    private AgedmallStoreMapper agedmallStoreMapper;
    @Resource
    private GoodsRejectedServiceImpl goodsRejectedServiceImpl;
    @Resource
    private AgedmallLgBusiImgMapper agedmallLgBusiImgMapper;
    @Resource
    private AgedmallCloudHouseMapper agedmallCloudHouseMapper;
    @Resource
    private TakeOrderServiceImpl takeOrderServiceImpl;
    @Resource
    private OrderStateService orderStateService;
    @Resource
    private LogisticsMapper logisticsMapper;
    @Resource
    private AgedmallLgRfidGoodsCurStatMapper agedmallLgRfidGoodsCurStatMapper;
    @Resource
    private RefusalToSignServiceImpl refusalToSignServiceImpl;
    @Resource
    private GoodsChangeServiceImpl goodsChangeServiceImpl;
    @Resource
    private AgedmallShopMapper agedmallShopMapper;
    @Resource
    private AgedmallGoodsEquMapper agedmallGoodsEquMapper;
    @Resource
    private AgedmallLgThirdLogisRecordMapper agedmallLgThirdLogisRecordMapper;
    @Resource
    private LitemallOrderMapper litemallOrderMapper;
    @Resource
    private LitemallOrderService litemallOrderService;
    @Resource
    private LogisticsGoodsUtil logisticsGoodsUtil;
    @Resource
    private AgedmallLgGoodsSignForRecordMapper agedmallLgGoodsSignForRecordMapper;
    @Resource
    private AgedmallLgMissionManRecordMapper agedmallLgMissionManRecordMapper;
    @Resource
    private InventoryService inventoryService;
    @Resource
    private AgedmallStoreGoodsMapper agedmallStoreGoodsMapper;
    @Resource
    private AgedmallAnnouncerBaseInfoService agedmallAnnouncerBaseInfoService;
    @Resource
    private AgedmallLgMissionService agedmallLgMissionService;

    @Override
    public List<Integer> getorderGoodsIds(String lgContent) {
        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(lgContent);
        List<Integer> orderGoodsId = new ArrayList<>();
        commonData.getGoodsDataList().forEach(goods -> orderGoodsId.add(goods.getOrderGoodsId()));
        return orderGoodsId;
    }


    /**
     * 获取配送模式 0-物流  1-自营
     */
    public Integer getOrderGoodsDeliveryMode(String lgContent){
        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(lgContent);
        Integer orderGoodsId=commonData.getGoodsDataList().get(0).getOrderGoodsId();
        LitemallOrderGoods orderGoods=litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId);
        AgedmallStoreGoods storeGoods=agedmallStoreGoodsMapper.selectByPrimaryKey(orderGoods.getStoreGoodsId().longValue());
        return storeGoods.getSameCitySendType();
    }


    /**
     * 确认收货增加签收表
     */

    @Override
    public void insertSignInConfirm(String bigOrderSn, String childOrderCode, Integer userId) {
        AgedmallLgBaseInfoExample baseInfoExample = new AgedmallLgBaseInfoExample();
        baseInfoExample.or().andOrderCodeEqualTo(bigOrderSn);
        List<AgedmallLgBaseInfo> agedmallLgBaseInfos = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(baseInfoExample);
        for (int i = 0; i < agedmallLgBaseInfos.size(); i++) {
            AgedmallLgBaseInfo baseInfo = agedmallLgBaseInfos.get(i);
            List<Integer> orderGoodsId = getorderGoodsIds(baseInfo.getLgContent());
            LitemallOrderGoods orderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId.get(0));
            if (orderGoods.getChildOrderCode().equals(childOrderCode)) {
                for (int j = 0; j < orderGoodsId.size(); j++) {
                    AgedmallLgGoodsSignForRecord goodsSignForRecord = new AgedmallLgGoodsSignForRecord();
                    goodsSignForRecord.setCreatedTime(LocalDateTime.now());
                    goodsSignForRecord.setLgBaseInfoId(baseInfo.getId());
                    goodsSignForRecord.setUid(userId.longValue());
                    goodsSignForRecord.setState(1);
                    goodsSignForRecord.setGoodsId(orderGoodsId.get(j).longValue());
                    goodsSignForRecord.setSignForTime(LocalDateTime.now());
                    goodsSignForRecord.setOrderCode(childOrderCode);
                    goodsSignForRecord.setUserType(1);
                    agedmallLgGoodsSignForRecordMapper.insertSelective(goodsSignForRecord);
                }
                break;
            }
        }

    }


    /**
     * 修改lgrfid表状态-配送完成
     *
     * @param lgContent
     * @return true 是 false 否
     */
    public void changeLgRfidState(String lgContent) {
        List<Integer> orderGoodsIds = getorderGoodsIds(lgContent);
        List<LogisticsGoodsTypeData> logisticsGoodsTypeData = logisticsMapper.selectGoodsTypeByOrderGoodsId(orderGoodsIds);
        logisticsGoodsTypeData.forEach(logisticsGoods -> {
            if (StrUtil.isNotBlank(logisticsGoods.getRfid())) {
                List<String> rfids = Arrays.asList(logisticsGoods.getRfid().split(","));

                Integer state = 0;
                //租赁
                if (logisticsGoods.getGoodsType().equals("lease")) {
                    state = LogisticsRfidStateEnum.LEASE.getCode();
                }
                //售卖
                else {
                    state = LogisticsRfidStateEnum.IS_SALE.getCode();
                }
                if (logisticsGoods.getType() == 1 || logisticsGoods.getType() == 2) {
                    AgedmallLgRfidGoodsCurStatExample curStatExample = new AgedmallLgRfidGoodsCurStatExample();
                    curStatExample.or().andTypeEqualTo(logisticsGoods.getType()).andRfidIn(rfids);
                    AgedmallLgRfidGoodsCurStat goodsCurStat = new AgedmallLgRfidGoodsCurStat();
                    goodsCurStat.setCurStat(state);
                    agedmallLgRfidGoodsCurStatMapper.updateByExampleSelective(goodsCurStat, curStatExample);
                }
            }
        });
    }


    @Override
    public void updateOrderGoodsStat(String lgContent, Integer state) {
        List<Integer> orderGoodsId = getorderGoodsIds(lgContent);
        orderStateService.modifyOrderGoodsStateBatch(orderGoodsId, state);
    }

    @Override
    public Map<String, List<String>> getAllRfidBybaseInfoId(String lgContent) {
        List<String> locksRfids = new ArrayList<>();
        List<String> cabinetRfids = new ArrayList<>();
        List<Integer> orderGoodsId = getorderGoodsIds(lgContent);
        LitemallOrderGoodsExample orderGoodsExample = new LitemallOrderGoodsExample();
        orderGoodsExample.or().andIdIn(orderGoodsId);
        List<LitemallOrderGoods> litemallOrderGoods = litemallOrderGoodsMapper.selectByExample(orderGoodsExample);
        Map<Integer, List<LitemallOrderGoods>> collect = litemallOrderGoods.stream().collect(Collectors.groupingBy(LitemallOrderGoods::getStockType));
        collect.forEach((key, value) -> {
            List<LitemallOrderGoods> orderGoodsList = value;
            List<String> ids = new ArrayList<>();
            orderGoodsList.forEach(orderGood -> {
                if (StrUtil.isNotBlank(orderGood.getRfid())) {
                    List<String> ogList = Arrays.asList(orderGood.getRfid().split(","));
                    ids.addAll(ogList);
                }
            });
            //链条锁
            if (key == 1) {
                locksRfids.addAll(ids);
            }
            //衣柜锁
            else if (key == 2) {
                cabinetRfids.addAll(ids);
            }
        });
        Map<String, List<String>> backMap = new HashMap<>();
        backMap.put("lock", locksRfids);
        backMap.put("cabinet", cabinetRfids);
        return backMap;
    }

    @Override
    public AgedmallLgReceiveOrder insertReceiveOrder(AgedmallLgBaseInfo agedmallLgBaseInfo, Integer deliveryManId, Integer receiverType, Integer execType
            , Long missionId) {
        AgedmallLgReceiveOrder receiveOrder = new AgedmallLgReceiveOrder();
        if (deliveryManId != null) {
            AgedmallDeliveryManInfo manInfo = agedmallDeliveryManInfoMapper.selectByPrimaryKey(deliveryManId);
            receiveOrder.setUserName(manInfo.getUsername());
            receiveOrder.setPhone(manInfo.getPhone());
        }
        receiveOrder.setLgBaseInfoId(agedmallLgBaseInfo.getId());
        receiveOrder.setMissionId(missionId);
        receiveOrder.setReceiveTime(LocalDateTime.now());
        receiveOrder.setOrderCode(agedmallLgBaseInfo.getOrderCode());
        receiveOrder.setReceiveType(receiverType == null ? 1 : receiverType);
        receiveOrder.setLgExecType(execType == null ? 1 : execType);
        receiveOrder.setCreatedTime(LocalDateTime.now());
        receiveOrder.setCreatedBy("auto");
        agedmallLgReceiveOrderMapper.insert(receiveOrder);
        return receiveOrder;
    }

    @Override
    public AgedmallLgBusiRecord insertBusiRecord(Long missionId, Long receiverOrderId, Integer missionType, String orderCode, Integer busiStat) {
        AgedmallLgBusiRecord agedmallLgBusiRecord = new AgedmallLgBusiRecord();
        agedmallLgBusiRecord.setReceiveOrderId(receiverOrderId);
        agedmallLgBusiRecord.setMissionId(missionId);
        agedmallLgBusiRecord.setBusiTime(LocalDateTime.now());
        agedmallLgBusiRecord.setBusiStat(busiStat == null ? 1 : busiStat);
        agedmallLgBusiRecord.setLgType(missionType);
        agedmallLgBusiRecord.setOrderCode(orderCode);
        agedmallLgBusiRecord.setCreatedBy("auto");
        agedmallLgBusiRecord.setCreatedTime(LocalDateTime.now());
        agedmallLgBusiRecordMapper.insert(agedmallLgBusiRecord);
        return agedmallLgBusiRecord;
    }

    @Override
    public void insertBusiImg(Long busiId, Integer imgType, String imgUrls) {
        AgedmallLgBusiImg agedmallLgBusiImg = new AgedmallLgBusiImg();
        agedmallLgBusiImg.setCreatedTime(LocalDateTime.now());
        agedmallLgBusiImg.setLgBusiId(busiId);
        agedmallLgBusiImg.setImgType(imgType);
        agedmallLgBusiImg.setUrl(imgUrls);
        agedmallLgBusiImgMapper.insert(agedmallLgBusiImg);
    }

    @Override
    public String base64ToUrl(List<String> base64Img) {
        if(base64Img == null || base64Img.size() == 0) {
            return null;
        }
        String path = "app/logistics/";
        String realPath = "";
        List<String> ossUrls = new ArrayList<>();
        try {
            if (SystemUtil.isWindows()) {
                realPath = UploadConstant.WINDOS_BASE_UPLOAD_URL + path;
            } else if (SystemUtil.isMacOS() || SystemUtil.isMacOSX()) {
                realPath = UploadConstant.MAC_BASE_UPLOAD_URL + path;
            } else {
                realPath = UploadConstant.LINUX_BASE_UPLOAD_URL + path;
            }
            for (int i = 0; i < base64Img.size(); i++) {
                String ossUrl = "";

                String fileName = "uploadLogistics-" + IdUtil.fastSimpleUUID() + ".jpg";
                FileUtil.mkdir(new File(realPath));
                String savePath = realPath + fileName;
                String ossPath = path + fileName;
                String isSave = Base64Util.generateImage(base64Img.get(i).substring(23), savePath);
                if (StrUtil.isNotBlank(isSave)) {
                    return null;
                }
                OssUtil ossUtil = new OssUtil();
                //TODO 上传到oss
                ossUrl = ossUtil.uploadFile(savePath, ossPath);
                ossUrls.add(ossUrl);
            }
        } catch (Exception e) {
            logger.error("图片转换失败：{}", e);
            return null;
        }

        return String.join(",", ossUrls);
    }


    /**
     * 修改rfid最后订单
     */
    public void updateLgRfidLastOrderCode(String orderCode, Integer baseInfoId) {
        List<AgedmallLgBaseInfo> agedmallLgBaseInfoList = new ArrayList<>();
        if (StrUtil.isNotBlank(orderCode)) {
            agedmallLgBaseInfoList = logisticsBaseServiceAbstractImpl.getAgedmallLgBaseInfosByOrderCode(orderCode);
        } else if (baseInfoId != null) {
            agedmallLgBaseInfoList.add(agedmallLgBaseInfoMapper.selectByPrimaryKey(baseInfoId.longValue()));
        }

        agedmallLgBaseInfoList.forEach(lgbaseInfo -> {
            Map<String, List<String>> allRfidBybaseInfoId = getAllRfidBybaseInfoId(lgbaseInfo.getLgContent());
            List<String> lock = allRfidBybaseInfoId.get("lock");
            List<String> cabinet = allRfidBybaseInfoId.get("cabinet");
            //更新物品rfid最后的订单号
            if (!lock.isEmpty()) {
                agedMallOrderDbService.updateRfidCurOrderCode(orderCode, lock, 1);
            }
            if (!cabinet.isEmpty()) {
                agedMallOrderDbService.updateRfidCurOrderCode(orderCode, cabinet, 2);
            }
        });
    }

    /**
     * 云仓判断，如果下单时是云仓，配货员直接默认选择，不需要抢单
     */
    @Override
    public void isCloudOrder(Integer baseInfoId, Integer missionId) {
        AgedmallLgBaseInfo baseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(baseInfoId.longValue());
        if (baseInfo.getWarehouseType() == 1) {
            takeOrderServiceImpl.chooseCloudDliveryMan(missionId);
        }
    }

    /**
     * 判断是否有软链，如果有，判断是否完成
     */
    public List<ChainLockPickup> checkChainIsFinish(String lgContent) {
        List<Integer> idList = getorderGoodsIds(lgContent);
        //链条锁
        LitemallOrderGoodsExample chainOrderGoodsExample = new LitemallOrderGoodsExample();
        chainOrderGoodsExample.or().andIdIn(idList).andStockTypeEqualTo(1);
        List<LitemallOrderGoods> chainOrderGoods = litemallOrderGoodsMapper.selectByExample(chainOrderGoodsExample);
        List<ChainLockPickup> backChainLock = new ArrayList<>();
        if (!chainOrderGoods.isEmpty()) {
            chainOrderGoods.forEach(chain -> {
                String[] rfidList = chain.getRfid().split(",");
                List<Integer> rfidsList = new ArrayList<>();
                List<Long> longRfidsList = new ArrayList<>();
                for (int i = 0; i < rfidList.length; i++) {
                    rfidsList.add(Integer.parseInt(rfidList[i]));
                    longRfidsList.add(Long.parseLong(rfidList[i]));
                }
                List<ChainLockPickup> chainLockPickup = agedmallShopMapper.selectEquGoodsMessage(rfidsList);
                backChainLock.addAll(chainLockPickup);
                //获取配货状态
                AgedmallGoodsEquExample goodsEquExample = new AgedmallGoodsEquExample();
                goodsEquExample.or().andEquIdIn(longRfidsList).andTypeEqualTo(0).andDeletedEqualTo((byte) 0);
                List<AgedmallGoodsEqu> goodsEqus = agedmallGoodsEquMapper.selectByExample(goodsEquExample);
                for (int i = 0; i < backChainLock.size(); i++) {
                    backChainLock.get(i).setPid(i + 1);
                    for (int j = 0; j < goodsEqus.size(); j++) {
                        if (backChainLock.get(i).getEquId().equals(goodsEqus.get(j).getEquId().toString())) {
                            if (goodsEqus.get(j).getDistributionType() == 2) {
                                backChainLock.get(i).setPickUpStatus(1);
                            } else if (goodsEqus.get(j).getDistributionType() == 3) {
                                backChainLock.get(i).setPickUpStatus(2);
                            } else {
                                backChainLock.get(i).setPickUpStatus(0);
                            }
                        }
                    }
                }
            });
        }
        return backChainLock;
    }

    /**
     * 配货完成判断是否有医柜，如果有，判断是否完成
     */
    public List<MedicalLockPickup> checkCabinetIsFinish(String lgContent) {
        List<Integer> idList = getorderGoodsIds(lgContent);
        //链条锁
        LitemallOrderGoodsExample cabinetOrderGoodsExample = new LitemallOrderGoodsExample();
        cabinetOrderGoodsExample.or().andIdIn(idList).andStockTypeEqualTo(2);
        List<LitemallOrderGoods> cabinetOrderGoods = litemallOrderGoodsMapper.selectByExample(cabinetOrderGoodsExample);
        List<MedicalLockPickup> backCabinetLock = new ArrayList<>();
        if (!cabinetOrderGoods.isEmpty()) {
            cabinetOrderGoods.forEach(cabinet -> {
                String[] rfidList = cabinet.getRfid().split(",");
                List<String> rfidsList = new ArrayList<>(Arrays.asList(rfidList));
                List<MedicalLockPickup> medicalLockPickups = agedmallShopMapper.selectMedicalLockGoodsMessage(rfidsList);
                backCabinetLock.addAll(medicalLockPickups);
            });
        }
        return backCabinetLock;
    }

    /**
     * 根据子订单创建物流基本信息
     * @param bigOrder 大订单信息，可以为空
     * @param orderItem 子订单信息，不能为空
     * @param userBackAddress 归还地址信息，可以为空
     * @return
     */
    public AgedmallLgBaseInfo createLgBaseInfoByOrderItem(LitemallOrder bigOrder, LitemallOrderItem orderItem, LogisticsBackUserAddressData userBackAddress, Integer lgType, Integer lgStat) {
        if(orderItem == null) {
            return null;
        }
        if(bigOrder == null) {
            bigOrder = litemallOrderService.findOrderByOrderCode(orderItem.getOrderCode());
        }
        LitemallOrderGoodsExample orderGoodsExample = new LitemallOrderGoodsExample();
        orderGoodsExample.or().andChildOrderCodeEqualTo(orderItem.getChildOrderCode());
        List<LitemallOrderGoods> orderGoodsUseIdList = litemallOrderGoodsMapper.selectByExample(orderGoodsExample);
        List<Integer> orderGoodsIdList = new ArrayList<>();
        orderGoodsUseIdList.forEach(orderGoodss -> orderGoodsIdList.add(orderGoodss.getId()));

        // 添加物流节点
        AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
        agedmallLgBaseInfo.setOrderCode(bigOrder.getOrderSn());
        agedmallLgBaseInfo.setLgType(lgType);
        agedmallLgBaseInfo.setLgContent(logisticsGoodsUtil.toJsonStringByOrderGoodsId(orderGoodsIdList, userBackAddress));
        agedmallLgBaseInfo.setUserName(bigOrder.getConsignee());
        agedmallLgBaseInfo.setPhone(bigOrder.getMobile());
        agedmallLgBaseInfo.setAddresss(bigOrder.getAddress());
        agedmallLgBaseInfo.setWarehouseType(orderGoodsUseIdList.get(0).getStockType() == 3 ? 1 : 0);
        Integer noticeType = 0;
        if (orderGoodsUseIdList.get(0).getStockType() == 3) {
            AgedmallCloudHouse cloudHouse = agedmallCloudHouseMapper.selectByPrimaryKey(orderGoodsUseIdList.get(0).getStoreId());
            agedmallLgBaseInfo.setWarehouseAddress(cloudHouse.getAddressDetail());
            agedmallLgBaseInfo.setStoreId(cloudHouse.getId());
            noticeType = 2;
        } else {
            AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(orderGoodsUseIdList.get(0).getStoreId().longValue());
            agedmallLgBaseInfo.setWarehouseAddress(store.getAddressDetail());
            agedmallLgBaseInfo.setStoreId(store.getId().intValue());
            AgedmallAnnouncerBaseInfo announcerBaseInfo = agedmallAnnouncerBaseInfoService.queryByStoreIdAndType(store.getId().intValue(), 0);
            if (store.getDeliveryMode() == 2 && null != announcerBaseInfo) {
                noticeType = 2;
            } else {
                noticeType = 1;
            }
        }
        agedmallLgBaseInfo.setNoticeType(noticeType);
        agedmallLgBaseInfo.setLgStat(lgStat);
        agedmallLgBaseInfo.setLgIsOver(0);
        agedmallLgBaseInfoMapper.insertSelective(agedmallLgBaseInfo);
        return agedmallLgBaseInfo;
    }

    public List<AgedmallLgBaseInfo> createLgBaseInfo(LitemallOrder bigOrder, List<LitemallOrderItem> itemList, LogisticsBackUserAddressData userBackAddress, Integer lgType, Integer lgStat) {
        List<AgedmallLgBaseInfo> baseInfoList = new ArrayList<>();
        for (LitemallOrderItem orderItem : itemList) {
            AgedmallLgBaseInfo agedmallLgBaseInfo = createLgBaseInfoByOrderItem(bigOrder, orderItem, userBackAddress, lgType, lgStat);
            baseInfoList.add(agedmallLgBaseInfo);
        }
        return baseInfoList;
    }

    /**
     * 根据大订单号创建物流基本信息
     * @param orderCode
     * @return
     */
    public List<AgedmallLgBaseInfo> createLgBaseInfoByOrderCode(String orderCode, Integer lgType, Integer lgStat) {
        LitemallOrder bigOrder = litemallOrderService.findOrderByOrderCode(orderCode);
        List<LitemallOrderItem> itemList =  litemallOrderService.getOrderItemListByBigOrderCode(orderCode);
        return createLgBaseInfo(bigOrder, itemList, null, lgType, lgStat);
    }

    /**
     * 创建任务
     *
     * @param orderCode
     * @param baseInfoId
     * @param type
     * @return 调用通知服务的 missionId集合
     */
    @Override
    public List<Integer> createMission(String orderCode, Integer baseInfoId, Integer type) {
        List<Integer> missionIds = new ArrayList<>();
        if (orderCode != null) {
            //批量的插入
            missionIds = logisticsBaseServiceAbstractImpl.insertIntoMissonByOrderCode(orderCode, type);
        } else if (baseInfoId != null) {
            //单个的插入
            missionIds = logisticsBaseServiceAbstractImpl.insertIntoOneMission(baseInfoId, type);
        }
        return missionIds;
    }

    /**
     * 创建任务是否手动，即有管理系统触发
     *
     * @param orderCode
     * @param baseInfoId
     * @param type
     * @param isManual
     * @return
     */
    @Override
    public List<Integer> createMissionManual(String orderCode, Integer baseInfoId, Integer type, boolean isManual) {
        List<Integer> missionIds = new ArrayList<>();
        if (orderCode != null) {
            //批量的插入
            missionIds = logisticsBaseServiceAbstractImpl.insertIntoMissonByOrderCodeExec(orderCode, type, isManual);
        } else if (baseInfoId != null) {
            //单个的插入
            missionIds = logisticsBaseServiceAbstractImpl.insertIntoOneMissionExec(baseInfoId, type, isManual);
        }
        return missionIds;    }

    @Override
    public List<Integer> createMissionBackstage(String orderCode, Integer baseInfoId, Integer type) {
        List<Integer> missionIds = new ArrayList<>();
        if (orderCode != null) {
            //批量的插入
            missionIds = logisticsBaseServiceAbstractImpl.insertIntoMissonByOrderCodeBackstage(orderCode, type);
        } else if (baseInfoId != null) {
            //单个的插入
            missionIds = logisticsBaseServiceAbstractImpl.insertIntoOneMissionBackstage(baseInfoId, type);
        }
        return missionIds;
    }

    /**
     * 用户下单事件
     *
     * @param orderCode  用户小程序下单单号  (批量插入传)
     * @param baseInfoId 业务信息id  (单个插入传)
     * @param type       任务类型(
     *                   1-配货
     *                   2-送货
     *                   3-维护
     *                   4-退货
     *                   5-换货-取货
     *                   6-换货-配货
     *                   7-换货-送货
     *                   8-自提-配货
     *                   )
     */
    @Override
    public List<Integer> userCreateOrderEvent(String orderCode, Integer baseInfoId, Integer type) {
       return userCreateOrderEventByManual(orderCode, baseInfoId, type, false, null);
    }

    @Override
    public List<Integer> userCreateOrderEventByManual(String orderCode, Integer baseInfoId, Integer type, boolean isManual, String packageUserId) {
        //配货开始任务
        List<Integer> missionIds = createMissionManual(orderCode, baseInfoId, type, isManual);
        if(StringUtils.isNotBlank(packageUserId) && StringUtils.isNumeric(packageUserId)) {
           //配置指定的
            agedmallLgMissionService.addSelLgMissionUser(Long.parseLong(packageUserId), baseInfoId, LogisticsMissionTypeEnum.ALLOT.getCode());

        }
        //更新rfid最后订单 并且如果是云仓 直接选中默认配货员。。
        updateLgRfidLastOrderCode(orderCode, baseInfoId);

        if (missionIds.size() == 0) {
            logger.error("下单没有需要调用企业微信的任务:{}",orderCode);
        } else {
            ToLitemallBean toLitemallBean = new ToLitemallBean();
            toLitemallBean.setType(ReceiveOrderResultTypeEum.SENDNOTICE.getCode());
            toLitemallBean.setMissionId(missionIds);
            directExchangeProducer.send(JSONUtil.toJsonStr(toLitemallBean), DirectExchangeRabbitMQConfig.TO_LITEMALL_NOTICE);
        }
        return missionIds;
    }

    /**
     * 后台管理发货操作
     *
     * @param orderCode
     * @param baseInfoId
     * @param type
     * @return
     */
    @Override
    public List<Integer> backstageManagementToPlaceAnOrder(String orderCode, Integer baseInfoId, Integer type) {
        //配货开始任务
        List<Integer> missionIds = createMissionBackstage(orderCode, baseInfoId, type);
        //更新rfid最后订单 并且如果是云仓 直接选中默认配货员。。
        updateLgRfidLastOrderCode(orderCode, baseInfoId);

        return missionIds;

    }

    /**
     * 配货完成事件  配货完成 配送中
     * https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/image/1636515450(1)-1470230002149756928.jpg
     * @param missionId 任务id
     */
    @Override
    public List<ChainLockPickup> deployOverEvent(Integer missionId, List<String> imgs, List<PickUp> rfids, String expressCode, List<String> imgUrls,boolean isHospitalSelf) throws CheckException {
        //根据missionId更新物流信息
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());
        if (!agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.BUY_ALLOTING) &&
                !agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.CHANGE_ALLOTING) &&
                !agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.PICK_UP_ALLOTING)) {
            throw new BizException("不在配货状态");
        }
        if(!isHospitalSelf){
            //判断是否有软链，如果有，判断是否完成
            List<ChainLockPickup> chainLockPickups = checkChainIsFinish(agedmallLgBaseInfo.getLgContent());
            if (!chainLockPickups.isEmpty()) {
                for (ChainLockPickup chain : chainLockPickups) {
                    if (chain.getPickUpStatus() == 0) {
                        return chainLockPickups;
                    }
                }
            }
        }

        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);
        //更新状态
        List<Integer> missionList = new ArrayList<>();
        //修改当前baseInfo状态
        Integer baseInfoState = 0;
        if (lgMission.getType().equals(LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode()) && agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.PICK_UP_ALLOT_COMPLETE;
        } else if (lgMission.getType().equals(LogisticsMissionTypeEnum.ALLOT.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.BUY_ALLOT_COMPLETE;
        } else if (lgMission.getType().equals(LogisticsMissionTypeEnum.CHANGE_ALLOT.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.CHANGE_ALLOT_COMPLETE;
        }
        AgedmallLgReceiveOrderExample receiveOrderExample = new AgedmallLgReceiveOrderExample();
        receiveOrderExample.setOrderByClause("`created_time` DESC");
        receiveOrderExample.or().andLgBaseInfoIdEqualTo(agedmallLgBaseInfo.getId());
        AgedmallLgReceiveOrder receiveOrder = agedmallLgReceiveOrderMapper.selectOneByExample(receiveOrderExample);
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(lgMission.getId().longValue(), receiveOrder.getId(), lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 2);
        //保存拍照上传的图片
        //插入img表
        String url = "";
        if (imgUrls != null && imgUrls.size() > 0) {
            url = StringUtils.join(imgUrls, ",");
        } else {
            url = base64ToUrl(imgs);
            if (StrUtil.isBlank(url)) {
                logger.error("图片转换错误：{}", url);
                throw new BizException("图片转换错误");
            }
        }
        insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
        //修改baseInfo状态
        agedmallLgBaseInfo.setLgStat(baseInfoState);
        if (agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())) {
            agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.END.getCode());
        }
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);

        //同步修改orderGoods状态
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), baseInfoState);
        //如果有医柜--更新新RFID
        if (rfids != null && !rfids.isEmpty()) {
            List<Integer> orderGoodsId = getorderGoodsIds(agedmallLgBaseInfo.getLgContent());
            LitemallOrderGoodsExample orderGoodsExample = new LitemallOrderGoodsExample();
            orderGoodsExample.or().andIdIn(orderGoodsId);
            List<LitemallOrderGoods> orderGoods = litemallOrderGoodsMapper.selectByExample(orderGoodsExample);
            orderStateService.replaceCabinetGoodsRfid(orderGoods, rfids);
        }
        if (agedmallLgBaseInfo.getWarehouseType() == WarehouseTypeEnum.STORE.getWarehouseType()) {
            AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(agedmallLgBaseInfo.getStoreId().longValue());
            //企业微信
            //TODO 配送模式还不需要判断baseInfo李做的配置,
            int deliveryMode = store.getDeliveryMode();
            executeDeliveryMission(deliveryMode, agedmallLgBaseInfo, lgMission, expressCode, store.getThirdLogisticsName());
        }
        //云仓
        else {
            logger.info("物流：{}，进入云仓配送;",agedmallLgBaseInfo.getId());
            AgedmallCloudHouse cloudHouse = agedmallCloudHouseMapper.selectByPrimaryKey(agedmallLgBaseInfo.getStoreId());
            missionList = createMission(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.DELIVERY.getCode());
            //TODO 如果是云仓  没有配第三方物流信息 默认顺丰
            thirdLogisEvent(missionList.get(0), expressCode, "顺丰", 1);
        }
        return null;
    }

    /**
     * 执行配送任务
     * @param deliveryMode
     * @param agedmallLgBaseInfo
     * @param lgMission 配货的任务信息
     * @param expressCode
     * @param thirdLogisticName
     * @throws CheckException
     */
    public void executeDeliveryMission(int deliveryMode, AgedmallLgBaseInfo agedmallLgBaseInfo, AgedmallLgMission lgMission, String expressCode, String thirdLogisticName) throws CheckException {
        List<Integer> missionList = new ArrayList<>();
        Long lgBaseInfoId = agedmallLgBaseInfo.getId();
        //获取门店商品配送设置
        Integer orderGoodsDeliveryMode=getOrderGoodsDeliveryMode(agedmallLgBaseInfo.getLgContent());
        if ((orderGoodsDeliveryMode==1&&(deliveryMode == StoreDeliveryModeEnum.SORT.getDeliveryMode() || deliveryMode == StoreDeliveryModeEnum.ALL.getDeliveryMode())) && !agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())) {
            deliverBySortOrAll(lgBaseInfoId.intValue(), lgMission.getType(), false);
        }
        //已经选定送货人
        else if (orderGoodsDeliveryMode==1&&deliveryMode == StoreDeliveryModeEnum.MANUAL.getDeliveryMode()) {
            logger.info("物流：{}，进入手动配送;",lgBaseInfoId);
            //TODO 已经选定操作需要在管理系统额外按钮触发
            //不是自提的时候才会有配送人员
            if (!agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())){
                Integer missonType = lgMission.getType();

                AgedmallLgMissionManRecordExample agedmallLgMissionManRecordExample = new AgedmallLgMissionManRecordExample();
                agedmallLgMissionManRecordExample.or().andBaseInfoIdEqualTo(lgBaseInfoId).andMissionTypeEqualTo(missonType);
                AgedmallLgMissionManRecord agedmallLgMissionManRecord = agedmallLgMissionManRecordMapper.selectOneByExampleSelective(agedmallLgMissionManRecordExample);

                deliverBySelUser(lgBaseInfoId.intValue(), agedmallLgMissionManRecord.getManId(), false);
            }
        } else if (orderGoodsDeliveryMode==0||deliveryMode == StoreDeliveryModeEnum.THIRD_LOGIC.getDeliveryMode()) {
            //TODO 通过快递，后续看快递怎么弄
            deliverByThirdLogistic(lgBaseInfoId.intValue(), expressCode, thirdLogisticName, false);
        }
    }

    /**
     * 按顺序或全部进行配送
     * @param lgBaseInfoId 配货生成的物流基本信息id
     * @param lgDeployMissionType 配货任务类型,是配货还是换货配货
     */
    public void deliverBySortOrAll(int lgBaseInfoId, Integer lgDeployMissionType, boolean isManual) {
        List<Integer> missionList = new ArrayList<>();
        logger.info("物流：{}，进入自动配送;",lgBaseInfoId);
        if (lgDeployMissionType.equals(LogisticsMissionTypeEnum.ALLOT.getCode())) {
            missionList = createMissionManual(null, lgBaseInfoId, LogisticsMissionTypeEnum.DELIVERY.getCode(), isManual);
        } else if (lgDeployMissionType.equals(LogisticsMissionTypeEnum.CHANGE_ALLOT.getCode())) {
            missionList = createMissionManual(null, lgBaseInfoId, LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode(), isManual);
        }
        //状态更新完成后调用企业微信进行发货抢单
        if (missionList.isEmpty()) {
            logger.error("配货完成调用企业微信抢单失败：{}", lgBaseInfoId);
        } else {
            ToLitemallBean toLitemallBean = new ToLitemallBean();
            toLitemallBean.setType(ReceiveOrderResultTypeEum.SENDNOTICE.getCode());
            toLitemallBean.setMissionId(missionList);
            directExchangeProducer.send(JSONUtil.toJsonStr(toLitemallBean), DirectExchangeRabbitMQConfig.TO_LITEMALL_NOTICE);
        }
    }

    /**
     * 按指定人进行配送
     * @param lgBaseInfoId 配货生成的物流基本信息id
     */
    public void deliverBySelUser(int lgBaseInfoId, Long selUseId, boolean isManual) {
        List<Integer> missionList = createMissionManual(null, lgBaseInfoId, LogisticsMissionTypeEnum.DELIVERY.getCode(), isManual);

        receiveOrderEvent(selUseId.intValue(), missionList.get(0),null);

        //接单
        //物流 -手动分配配货配送人员记录表 改为已使用状态
        AgedmallLgMissionManRecord agedmallLgMissionManRecord = new AgedmallLgMissionManRecord();
        agedmallLgMissionManRecord.setManId(selUseId);
        agedmallLgMissionManRecord.setIsUse(1);
        AgedmallLgMissionManRecordExample manRecordExample = new AgedmallLgMissionManRecordExample();
        manRecordExample.createCriteria().andManIdEqualTo(selUseId);
        agedmallLgMissionManRecordMapper.updateByExampleSelective(agedmallLgMissionManRecord, manRecordExample);
    }

    /**
     * 通过第三方快递进行配送
     * @param lgBaseInfoId
     * @param expressCode
     * @param thirdLogisticName
     * @param isManual
     * @throws CheckException
     */
    public void deliverByThirdLogistic(int lgBaseInfoId, String expressCode, String thirdLogisticName, boolean isManual) throws CheckException {
        List<Integer> missionList = createMission(null, lgBaseInfoId, LogisticsMissionTypeEnum.DELIVERY.getCode());
        thirdLogisEvent(missionList.get(0), expressCode, thirdLogisticName, LgTakeOrderRecordTypeEnum.DELIVER.getType());
    }

    /**
     * 配送异常
     */
    public void deployOverEventException(List<String> imgs,Integer missionId,String errorReason,String errorRemark){
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(LgMissionIsOverEum.EXCEPTION.getCode());
        lgMission.setErrorReason(errorReason);
        lgMission.setErrorRemark(errorRemark);
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());
        AgedmallLgReceiveOrderExample receiveOrderExample = new AgedmallLgReceiveOrderExample();
        receiveOrderExample.setOrderByClause("`created_time` DESC");
        receiveOrderExample.or().andLgBaseInfoIdEqualTo(agedmallLgBaseInfo.getId());
        AgedmallLgReceiveOrder receiveOrder = agedmallLgReceiveOrderMapper.selectOneByExample(receiveOrderExample);
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(lgMission.getId().longValue(), receiveOrder.getId(), lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 3);

        //插入img表
        String url = "";
        if (imgs != null && imgs.size() > 0) {
            url = base64ToUrl(imgs);
            if (StrUtil.isBlank(url)) {
                logger.error("图片转换错误：{}", url);
                throw new BizException("图片转换错误");
            }
            insertBusiImg(agedmallLgBusiRecord.getId(), 3, url);
        }
        Integer lgStat=LgBaseInfoStatConstant.STATE_EXCEPTION;
        agedmallLgBaseInfo.setLgStat(lgStat);
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), lgStat);
    }


    /**
     * 换货配货完成事件  配货完成 配送中
     *
     * @param missionId 任务id
     */
    @Override
    public List<ChainLockPickup> exchangeDeployOverEvent(Integer missionId, List<String> imgs, List<PickUp> rfids, String expressCode, List<String> imgUrls) throws CheckException {
        //根据missionId更新物流信息
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());
        if (!agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.BUY_ALLOTING) &&
                !agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.CHANGE_SENDING) &&
                !agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.PICK_UP_ALLOTING)) {
            throw new BizException("不在配货状态");
        }

        //判断是否有软链，如果有，判断是否完成
        List<ChainLockPickup> chainLockPickups = checkChainIsFinish(agedmallLgBaseInfo.getLgContent());
        if (!chainLockPickups.isEmpty()) {
            for (ChainLockPickup chain : chainLockPickups) {
                if (chain.getPickUpStatus() == 0) {
                    return chainLockPickups;
                }
            }
        }

        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);
        //更新状态
        List<Integer> missionList = new ArrayList<>();
        //修改当前baseInfo状态
        Integer baseInfoState = 0;
        if (lgMission.getType().equals(LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode()) && agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.PICK_UP_ALLOT_COMPLETE;
        } else if (lgMission.getType().equals(LogisticsMissionTypeEnum.ALLOT.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.BUY_ALLOT_COMPLETE;
        } else if (lgMission.getType().equals(LogisticsMissionTypeEnum.CHANGE_ALLOT.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.CHANGE_ALLOT_COMPLETE;
        }
        AgedmallLgReceiveOrderExample receiveOrderExample = new AgedmallLgReceiveOrderExample();
        receiveOrderExample.setOrderByClause("`created_time` DESC");
        receiveOrderExample.or().andLgBaseInfoIdEqualTo(agedmallLgBaseInfo.getId());
        AgedmallLgReceiveOrder receiveOrder = agedmallLgReceiveOrderMapper.selectOneByExample(receiveOrderExample);
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(lgMission.getId().longValue(), receiveOrder.getId(), lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 2);
        //保存拍照上传的图片
        //插入img表
        String url = "";
        if (imgUrls != null && imgUrls.size() > 0) {
            url = StringUtils.join(imgUrls, ",");
        } else {
            url = base64ToUrl(imgs);
            if (StrUtil.isBlank(url)) {
                logger.error("图片转换错误：{}", url);
                throw new BizException("图片转换错误");
            }
        }
        insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
        //修改baseInfo状态
        agedmallLgBaseInfo.setLgStat(baseInfoState);
        if (agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())) {
            agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.END.getCode());
        }
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);

        //同步修改orderGoods状态
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), baseInfoState);
        //如果有医柜--更新新RFID
        if (rfids != null && !rfids.isEmpty()) {
            List<Integer> orderGoodsId = getorderGoodsIds(agedmallLgBaseInfo.getLgContent());
            LitemallOrderGoodsExample orderGoodsExample = new LitemallOrderGoodsExample();
            orderGoodsExample.or().andIdIn(orderGoodsId);
            List<LitemallOrderGoods> orderGoods = litemallOrderGoodsMapper.selectByExample(orderGoodsExample);
            orderStateService.replaceCabinetGoodsRfid(orderGoods, rfids);
        }
        if (agedmallLgBaseInfo.getWarehouseType() == WarehouseTypeEnum.STORE.getWarehouseType()) {
            AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(agedmallLgBaseInfo.getStoreId().longValue());
            //企业微信
            //TODO 配送模式还不需要判断baseInfo李做的配置,
            int deliveryMode = store.getDeliveryMode();
            //获取门店商品配送设置
            Integer orderGoodsDeliveryMode=getOrderGoodsDeliveryMode(agedmallLgBaseInfo.getLgContent());
            //已经选定送货人
             if (orderGoodsDeliveryMode==1&&deliveryMode == StoreDeliveryModeEnum.MANUAL.getDeliveryMode()) {
                //TODO 已经选定操作需要在管理系统额外按钮触发
                //不是自提的时候才会有配送人员
                if (!agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())){
                    missionList = createMissionBackstage(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode());
                    AgedmallLgMissionManRecordExample agedmallLgMissionManRecordExample = new AgedmallLgMissionManRecordExample();
                    agedmallLgMissionManRecordExample.or().andBaseInfoIdEqualTo(agedmallLgBaseInfo.getId()).andMissionTypeEqualTo(LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode());
                    //agedmallLgMissionManRecordExample.setOrderByClause("`id` DESC");
                    //未使用
                    //agedmallLgMissionManRecordExample.or().andIsUseEqualTo(0);
                    AgedmallLgMissionManRecord agedmallLgMissionManRecord = agedmallLgMissionManRecordMapper.selectOneByExampleSelective(agedmallLgMissionManRecordExample);
                    //接单
                    receiveOrderEvent(agedmallLgMissionManRecord.getManId().intValue(),missionList.get(0),null);
                    agedmallLgMissionManRecord.setIsUse(1);
                    //物流 -手动分配配货配送人员记录表 改为已使用状态
                    agedmallLgMissionManRecordMapper.updateByPrimaryKey(agedmallLgMissionManRecord);
                }


            } else if (orderGoodsDeliveryMode==0||deliveryMode == StoreDeliveryModeEnum.THIRD_LOGIC.getDeliveryMode()) {
                 missionList = createMissionBackstage(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode());
                //TODO 通过快递，后续看快递怎么弄
                thirdLogisEvent(missionList.get(0), expressCode, store.getThirdLogisticsName(), 1);
            }
        }
        //云仓
        else {
            AgedmallCloudHouse cloudHouse = agedmallCloudHouseMapper.selectByPrimaryKey(agedmallLgBaseInfo.getStoreId());
            missionList = createMissionBackstage(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode());
            //TODO 如果是云仓  没有配第三方物流信息 默认顺丰
            thirdLogisEvent(missionList.get(0), expressCode, "顺丰", 1);
        }
        return null;
    }



    /**
     * 接单事件 接单成功-待配送
     *
     * @param manId       接单人id
     * @param missionId   任务id
     * @param messageType takeOrder类型
     */
    @Override
    public void receiveOrderEvent(Integer manId, Integer missionId, Integer messageType) {
        //更新数据
        AgedmallLgMission mission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(mission.getBaseInfoId().longValue());
        Integer stat = LgBaseInfoStatConstant.waitToSendStat(agedmallLgBaseInfo.getLgType(), mission.getType());
        agedmallLgBaseInfo.setLgStat(stat);
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        //更新mission
        agedmallLgMissionMapper.updateByPrimaryKeySelective(mission);
        //新增agedmall_lg_receive_order
        insertReceiveOrder(agedmallLgBaseInfo, manId, 1, 1, missionId.longValue());
        //更改订单商品的状态
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), stat);


    }

    @Override
    public void startReceiveOrderEvent(Integer missionId) throws CheckException {
        logger.debug("开始接任务:{}", missionId);
        AgedmallLgMission mission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        mission.setMissionIsOver(LgMissionIsOverEum.START.getCode());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(mission.getBaseInfoId().longValue());

        String bigOrderCode = agedmallLgBaseInfo.getOrderCode();
        checkLgBaseOrderStat(bigOrderCode);
        Integer missionType = mission.getType();
        int lgType = agedmallLgBaseInfo.getLgType();
        String lgContent = agedmallLgBaseInfo.getLgContent();
        int lgIsOver = agedmallLgBaseInfo.getLgIsOver();
        checkBackIsCancel(lgIsOver);

        Integer stat = LgBaseInfoStatConstant.startToSendStat(lgType, missionType);
        agedmallLgBaseInfo.setLgStat(stat);
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        //更新mission
        agedmallLgMissionMapper.updateByPrimaryKeySelective(mission);
        AgedmallLgReceiveOrderExample receiveOrderExample = new AgedmallLgReceiveOrderExample();
        receiveOrderExample.or().andMissionIdEqualTo(mission.getId().longValue());
        AgedmallLgReceiveOrder receiveOrder = agedmallLgReceiveOrderMapper.selectOneByExample(receiveOrderExample);
        //新增
        insertBusiRecord(mission.getId().longValue(), receiveOrder.getId(), missionType, agedmallLgBaseInfo.getOrderCode(), 1);
        if (!missionType.equals(LogisticsMissionTypeEnum.MAINTAIN.getCode()) && !missionType.equals(LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode())) {
            //更改订单商品的状态
            updateOrderGoodsStat(lgContent, stat);
        }
    }


    /**
     * 配送完成事件
     *
     * @param missionId
     */
    @Override
    public void deliveryOverEvent(Integer missionId, List<String> imgs, List<String> imgsUrl) {
        //根据missionId更新物流信息
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());
        if (!agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.BUY_SENDING) &&
                !agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.CHANGE_SENDING)) {
            throw new BizException("不在送货状态");
        }
        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);
        //修改当前baseInfo状态
        Integer baseInfoState = 0;
        if (lgMission.getType().equals(LogisticsMissionTypeEnum.DELIVERY.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.BUY_SEND_COMPLETE;
        } else if (lgMission.getType().equals(LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.CHANGE_SEND_COMPLETE;
        }
        AgedmallLgReceiveOrderExample receiveOrderExample = new AgedmallLgReceiveOrderExample();
        receiveOrderExample.setOrderByClause("`created_time` DESC");
        receiveOrderExample.or().andLgBaseInfoIdEqualTo(agedmallLgBaseInfo.getId());
        AgedmallLgReceiveOrder receiveOrder = agedmallLgReceiveOrderMapper.selectOneByExample(receiveOrderExample);
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(lgMission.getId().longValue(), receiveOrder.getId(), lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 2);
        //保存拍照上传的图片
        //插入img表
        String url = "";
        if (imgsUrl != null && imgsUrl.size() > 0) {
            url = StringUtils.join(imgsUrl, ",");
        } else {
            if (imgs != null && imgs.size() > 0) {
                url = base64ToUrl(imgs);
                if (StrUtil.isBlank(url)) {
                    logger.error("图片转换错误：{}", url);
                    throw new BizException("图片转换错误");
                }
            }
        }

        insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
        //修改baseInfo状态
        agedmallLgBaseInfo.setLgStat(baseInfoState);
        agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.END.getCode());
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        //同步修改orderGoods状态
        if (!lgMission.getType().equals(LogisticsMissionTypeEnum.MAINTAIN.getCode()) && !lgMission.getType().equals(LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode())) {
            updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), baseInfoState);
            //如果有RFID。修改rdif相关状态
            changeLgRfidState(agedmallLgBaseInfo.getLgContent());
        }
    }

    /**
     * 换货配送完成事件
     *
     * @param missionId
     * @param imgs
     * @param imgsUrl
     */
    @Override
    public void exchageDeliveryOverEvent(Integer missionId, List<String> imgs, List<String> imgsUrl) {
        //根据missionId更新物流信息
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());
        if (!agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.BUY_SENDING) &&
                !agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.CHANGE_SENDING)) {
            throw new BizException("不在送货状态");
        }
        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);
        //修改当前baseInfo状态
        Integer baseInfoState = 0;
        if (lgMission.getType().equals(LogisticsMissionTypeEnum.DELIVERY.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.BUY_SEND_COMPLETE;
        } else if (lgMission.getType().equals(LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode())) {
            baseInfoState = LgBaseInfoStatConstant.CHANGE_SEND_COMPLETE;
        }
        AgedmallLgReceiveOrderExample receiveOrderExample = new AgedmallLgReceiveOrderExample();
        receiveOrderExample.setOrderByClause("`created_time` DESC");
        receiveOrderExample.or().andLgBaseInfoIdEqualTo(agedmallLgBaseInfo.getId());
        AgedmallLgReceiveOrder receiveOrder = agedmallLgReceiveOrderMapper.selectOneByExample(receiveOrderExample);
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(lgMission.getId().longValue(), receiveOrder.getId(), lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 2);
        //保存拍照上传的图片
        //插入img表
        String url = "";
        if (imgsUrl != null && imgsUrl.size() > 0) {
            url = StringUtils.join(imgsUrl, ",");
        } else {
            if (imgs != null && imgs.size() > 0) {
                url = base64ToUrl(imgs);
                if (StrUtil.isBlank(url)) {
                    logger.error("图片转换错误：{}", url);
                    throw new BizException("图片转换错误");
                }
            }
        }
        List<Integer> missionList = new ArrayList<>();
        insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
        //修改baseInfo状态
        agedmallLgBaseInfo.setLgStat(baseInfoState);
        agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.END.getCode());
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        //同步修改orderGoods状态
        if (!lgMission.getType().equals(LogisticsMissionTypeEnum.MAINTAIN.getCode()) && !lgMission.getType().equals(LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode())) {
            updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), baseInfoState);
            //如果有RFID。修改rdif相关状态
            changeLgRfidState(agedmallLgBaseInfo.getLgContent());
        }

        if (agedmallLgBaseInfo.getWarehouseType() == WarehouseTypeEnum.STORE.getWarehouseType()) {
            AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(agedmallLgBaseInfo.getStoreId().longValue());
            //创建换货取货任务
            //已经选定送货人
            int deliveryMode = store.getDeliveryMode();

            //获取门店商品配送设置
            Integer orderGoodsDeliveryMode=getOrderGoodsDeliveryMode(agedmallLgBaseInfo.getLgContent());

            if (orderGoodsDeliveryMode==1&&deliveryMode == StoreDeliveryModeEnum.MANUAL.getDeliveryMode()) {
                //TODO 已经选定操作需要在管理系统额外按钮触发
                //不是自提的时候才会有配送人员
                if (!agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())) {
                    missionList = createMissionBackstage(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode());
                    AgedmallLgMissionManRecordExample agedmallLgMissionManRecordExample = new AgedmallLgMissionManRecordExample();
                    agedmallLgMissionManRecordExample.or().andBaseInfoIdEqualTo(agedmallLgBaseInfo.getId()).andMissionTypeEqualTo(LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode());
                    //agedmallLgMissionManRecordExample.setOrderByClause("`id` DESC");
                    //未使用
                    //agedmallLgMissionManRecordExample.or().andIsUseEqualTo(0);
                    AgedmallLgMissionManRecord agedmallLgMissionManRecord = agedmallLgMissionManRecordMapper.selectOneByExampleSelective(agedmallLgMissionManRecordExample);
                    //接单
                    receiveOrderEvent(agedmallLgMissionManRecord.getManId().intValue(), missionList.get(0), null);
                    agedmallLgMissionManRecord.setIsUse(1);
                    //物流 -手动分配配货配送人员记录表 改为已使用状态
                    agedmallLgMissionManRecordMapper.updateByPrimaryKey(agedmallLgMissionManRecord);
                }
            }
        }
    }


    /**
     * 退货事件
     *
     * @param missionId
     * @param imgs
     */
    @Override
    public boolean rejectedGoodsEvent(Integer missionId, List<String> imgs) {
        //退货完成
      return goodsRejectedServiceImpl.goodsReturnCompleted(missionId, imgs);
    }

    /**
     * 换货事件
     */
    @Override
    public void exchangeGoodsEvent() {

    }

    /**
     * 拒绝签收
     *
     * @param missionId
     */
    @Override
    public void refuseGoodsEvent(Integer missionId) {
        //拒绝签收
        refusalToSignServiceImpl.refuseToSign(missionId);
    }

    @Override
    public void startReturnGoodsEvent(String bigOrderSn, Integer subOrderId, String expressId, String expressName) throws CheckException {
        LitemallOrder bigOrder = litemallOrderService.findOrderByOrderCode(bigOrderSn);
        LitemallOrderGoodsExample orderGoodsExample = new LitemallOrderGoodsExample();
        orderGoodsExample.or().andChildOrderIdEqualTo(Long.parseLong(subOrderId.toString()));
        List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsMapper.selectByExample(orderGoodsExample);
        List<Integer> orderGoodsIdList = new ArrayList<>();
        orderGoodsList.forEach(orderGoods -> orderGoodsIdList.add(orderGoods.getId()));

        AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
        agedmallLgBaseInfo.setOrderCode(bigOrderSn);
        agedmallLgBaseInfo.setLgType(3);
        agedmallLgBaseInfo.setLgContent(logisticsGoodsUtil.toJsonStringByOrderGoodsId(orderGoodsIdList, null));
        agedmallLgBaseInfo.setUserName(bigOrder.getConsignee());
        agedmallLgBaseInfo.setPhone(bigOrder.getMobile());
        agedmallLgBaseInfo.setAddresss(bigOrder.getAddress());
        agedmallLgBaseInfo.setWarehouseType(orderGoodsList.get(0).getStockType() == 3 ? 1 : 0);
        agedmallLgBaseInfo.setNoticeType(4);
        if (orderGoodsList.get(0).getStockType() == 3) {
            AgedmallCloudHouse cloudHouse = agedmallCloudHouseMapper.selectByPrimaryKey(orderGoodsList.get(0).getStoreId());
            agedmallLgBaseInfo.setWarehouseAddress(cloudHouse.getAddressDetail());
            agedmallLgBaseInfo.setStoreId(cloudHouse.getId());
        } else {
            AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(orderGoodsList.get(0).getStoreId().longValue());
            agedmallLgBaseInfo.setWarehouseAddress(store.getAddressDetail());
            agedmallLgBaseInfo.setStoreId(store.getId().intValue());
        }
        agedmallLgBaseInfo.setLgStat(LgBaseInfoStatConstant.RETURNING);
        agedmallLgBaseInfo.setLgIsOver(0);
        agedmallLgBaseInfoMapper.insertSelective(agedmallLgBaseInfo);
        List<Integer> mission = createMission(null, agedmallLgBaseInfo.getId().intValue(), 4);
        for (int i = 0; i < mission.size(); i++) {
            thirdLogisEvent(mission.get(i), expressId, expressName, 2);
        }
    }

    /**
     * 归还事件
     */
    @Override
    public void returnGoodsEvent(Integer missionId) {
        //上门取件归还(小程序推荐归还方式)
        //用户自行归还
        //用户通过第三方物流归还
    }

    /**
     * 归还完成事件
     *
     * @param missionId
     * @param imgs
     */
    @Override
    public boolean returnCompleteEvent(Integer missionId, List<String> imgs, List<String> imgsUrl) {
//        returnEquServiceImpl.returnComplete(missionId, imgs);
//        createMission(orderCode, baseInfoId, type);
        //根据missionId更新物流信息
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());
        List<ChainLockPickup> chainLockPickups = checkChainIsFinish(agedmallLgBaseInfo.getLgContent());
        //判断是否有软链，如果有，是否已经全部归还
        if (chainLockPickups != null && !chainLockPickups.isEmpty()) {
//            for (ChainLockPickup chain : chainLockPickups) {
//                if (chain.getPickUpStatus() != 2) {
//                    return false;
//                }
//            }
            //更新软链rfid状态
            List<Long> goodsEquList = new ArrayList<>();
            List<String> chainRfidList = new ArrayList<>();
            chainLockPickups.forEach(chain -> {
                goodsEquList.add(Long.parseLong(chain.getEquId()));
                chainRfidList.add(chain.getEquId());
            });
            AgedmallGoodsEquExample goodsEquExample = new AgedmallGoodsEquExample();
            goodsEquExample.or().andTypeEqualTo(0).andEquIdIn(goodsEquList);
            AgedmallGoodsEqu goodsEqu = new AgedmallGoodsEqu();
            goodsEqu.setDistributionType(0);
            agedmallGoodsEquMapper.updateByExampleSelective(goodsEqu, goodsEquExample);
        }


        List<MedicalLockPickup> medicalLockPickups = checkCabinetIsFinish(agedmallLgBaseInfo.getLgContent());
        //判断是否有医柜锁，如果有，是否已经全部归还
        if (!medicalLockPickups.isEmpty()) {
            for (MedicalLockPickup cabinet : medicalLockPickups) {
                if (cabinet.getState() != 2) {
                    return false;
                }
            }
        }

        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);
        //更新状态
        List<Integer> missionList = new ArrayList<>();
        //修改当前baseInfo状态
        Integer baseInfoState = LgBaseInfoStatConstant.LEASE_BACK;

        AgedmallLgReceiveOrderExample receiveOrderExample = new AgedmallLgReceiveOrderExample();
        receiveOrderExample.setOrderByClause("`created_time` DESC");
        receiveOrderExample.or().andLgBaseInfoIdEqualTo(agedmallLgBaseInfo.getId());
        AgedmallLgReceiveOrder receiveOrder = agedmallLgReceiveOrderMapper.selectOneByExample(receiveOrderExample);
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(lgMission.getId().longValue(), receiveOrder.getId(), lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 2);
        //保存拍照上传的图片
        //插入img表
        String url = "";
        if (imgsUrl != null && imgsUrl.size() > 0) {
            url = StringUtils.join(imgsUrl, ",");
            insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
        } else {
            if (imgs != null && !imgs.isEmpty()) {
                url = base64ToUrl(imgs);
                if (StrUtil.isBlank(url)) {
                    logger.error("图片转换错误：{}", url);
                    throw new BizException("图片转换错误");
                }
                insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
            }
        }

        //修改baseInfo状态
        agedmallLgBaseInfo.setLgStat(baseInfoState);
        agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.END.getCode());
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);


        //同步修改orderGoods状态
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), baseInfoState);

        //更新签收表
        List<Integer> orderGoodsId = getorderGoodsIds(agedmallLgBaseInfo.getLgContent());
        LitemallOrderGoods orderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId.get(0));
        LitemallOrder order = litemallOrderMapper.selectByPrimaryKey(orderGoods.getOrderId());
        for (int j = 0; j < orderGoodsId.size(); j++) {
            AgedmallLgGoodsSignForRecord goodsSignForRecord = new AgedmallLgGoodsSignForRecord();
            goodsSignForRecord.setCreatedTime(LocalDateTime.now());
            goodsSignForRecord.setLgBaseInfoId(agedmallLgBaseInfo.getId());
            goodsSignForRecord.setState(1);
            goodsSignForRecord.setGoodsId(orderGoodsId.get(j).longValue());
            goodsSignForRecord.setSignForTime(LocalDateTime.now());
            goodsSignForRecord.setOrderCode(order.getOrderSn());
            goodsSignForRecord.setUserType(1);
            agedmallLgGoodsSignForRecordMapper.insertSelective(goodsSignForRecord);
        }

        AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(agedmallLgBaseInfo.getStoreId().longValue());
        //企业微信
        //TODO 配送模式还不需要判断baseInfo李做的配置,
        int deliveryMode = store.getDeliveryMode();
        if ((deliveryMode == StoreDeliveryModeEnum.SORT.getDeliveryMode() || deliveryMode == StoreDeliveryModeEnum.ALL.getDeliveryMode()) && !agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())) {
            //企业微信
            missionList = createMission(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.MAINTAIN.getCode());
            //状态更新完成后调用企业微信进行维护抢单
            if (missionList.isEmpty()) {
                logger.error("归还完成调用企业微信抢单失败：{}", agedmallLgBaseInfo.getId());
            } else {
                ToLitemallBean toLitemallBean = new ToLitemallBean();
                toLitemallBean.setType(ReceiveOrderResultTypeEum.SENDNOTICE.getCode());
                toLitemallBean.setMissionId(missionList);
                directExchangeProducer.send(JSONUtil.toJsonStr(toLitemallBean), DirectExchangeRabbitMQConfig.TO_LITEMALL_NOTICE);
            }
        }else if (deliveryMode == StoreDeliveryModeEnum.MANUAL.getDeliveryMode()){
            missionList = createMissionBackstage(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.MAINTAIN.getCode());
            AgedmallLgMissionManRecordExample agedmallLgMissionManRecordExample = new AgedmallLgMissionManRecordExample();
            agedmallLgMissionManRecordExample.or().andBaseInfoIdEqualTo(agedmallLgBaseInfo.getId()).andMissionTypeEqualTo(LogisticsMissionTypeEnum.MAINTAIN.getCode());
            //agedmallLgMissionManRecordExample.setOrderByClause("`id` DESC");
            //未使用
            //agedmallLgMissionManRecordExample.or().andIsUseEqualTo(0);
            AgedmallLgMissionManRecord agedmallLgMissionManRecord = agedmallLgMissionManRecordMapper.selectOneByExampleSelective(agedmallLgMissionManRecordExample);
            //接单
            receiveOrderEvent(agedmallLgMissionManRecord.getManId().intValue(),missionList.get(0),null);
            agedmallLgMissionManRecord.setIsUse(1);
            //物流 -手动分配配货配送人员记录表 改为已使用状态
            agedmallLgMissionManRecordMapper.updateByPrimaryKey(agedmallLgMissionManRecord);
        }

        return true;
    }

    @Override
    public boolean cancelReturn(String orderSn, String childOrderCode) {
        AgedmallLgBaseInfoExample baseInfoExample = new AgedmallLgBaseInfoExample();
        baseInfoExample.or().andOrderCodeEqualTo(orderSn).andLgTypeEqualTo(LgBaseInfoLgType.GIVEBACK.getCode()).andLgIsOverNotEqualTo(LgBaseInfoIsOverEnum.CANCEL.getCode());
        LitemallOrderGoodsExample orderGoodsExample = new LitemallOrderGoodsExample();
        orderGoodsExample.or().andChildOrderCodeEqualTo(childOrderCode);
        List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsMapper.selectByExample(orderGoodsExample);
        List<Integer> orderGoodsIdList = new ArrayList<>();
        orderGoodsList.forEach(orderGoods -> orderGoodsIdList.add(orderGoods.getId()));
        List<AgedmallLgBaseInfo> agedmallLgBaseInfos = agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(baseInfoExample);
        for (int i = 0; i < agedmallLgBaseInfos.size(); i++) {
            List<Integer> integers = logisticsBaseServiceAbstractImpl.getorderGoodsIds(agedmallLgBaseInfos.get(i).getLgContent());
            for (int j = 0; j < orderGoodsIdList.size(); j++) {
                for (int k = 0; k < integers.size(); k++) {
                    if (orderGoodsIdList.get(j).equals(integers.get(k))) {
                        AgedmallLgMissionExample missionExample = new AgedmallLgMissionExample();
                        missionExample.or().andBaseInfoIdEqualTo(agedmallLgBaseInfos.get(i).getId().intValue());
                        AgedmallLgMission mission = new AgedmallLgMission();
                        mission.setMissionIsOver(LgMissionIsOverEum.CANCEL.getCode());
                        AgedmallLgBaseInfo baseInfo = agedmallLgBaseInfos.get(i);
                        baseInfo.setLgIsOver(LgBaseInfoIsOverEnum.CANCEL.getCode());
                        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(baseInfo);
                        agedmallLgMissionMapper.updateByExampleSelective(mission, missionExample);
                        return true;
                    }
                }
            }
        }

        return false;
    }


    /**
     * 维护事件
     */
    @Override
    public void maintainGoodsEvent(Integer missionId) {
        //发送通知->接单事件->进行维护->维护完成

    }

    /**
     * 维护完成事件
     *
     * @param missionId
     * @param imgs
     */
    @Override
    public void maintenanceCompletionEvent(Integer missionId, List<String> imgs, List<String> imgsUrl) {
//        maintainServiceImpl.equipmentMaintenanceCompleted(missionId, imgs);

        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());

        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);
        //修改当前baseInfo状态
        Integer baseInfoState = LgBaseInfoStatConstant.MAINTAIN_COMPLETE;

        AgedmallLgReceiveOrderExample receiveOrderExample = new AgedmallLgReceiveOrderExample();
        receiveOrderExample.setOrderByClause("`created_time` DESC");
        receiveOrderExample.or().andLgBaseInfoIdEqualTo(agedmallLgBaseInfo.getId());
        AgedmallLgReceiveOrder receiveOrder = agedmallLgReceiveOrderMapper.selectOneByExample(receiveOrderExample);
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(lgMission.getId().longValue(), receiveOrder.getId(), lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 2);
        //保存拍照上传的图片
        //插入img表
        if (imgsUrl != null && imgsUrl.size() > 0) {
            String url = StringUtils.join(imgsUrl, ",");
            insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
        } else {
            if (!imgs.isEmpty()) {
                String url = base64ToUrl(imgs);
                if (StrUtil.isBlank(url)) {
                    logger.error("图片转换错误：{}", url);
                    throw new BizException("图片转换错误");
                }
                insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
            }
        }
        //修改baseInfo状态
        agedmallLgBaseInfo.setLgStat(baseInfoState);
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);

        //如果有软链，软链返还库存
        returnChainInventory(agedmallLgBaseInfo.getLgContent());
    }

    public void returnChainInventory(String lgContent){
        List<Integer> idList = getorderGoodsIds(lgContent);
        //链条锁
        LitemallOrderGoodsExample chainOrderGoodsExample = new LitemallOrderGoodsExample();
        chainOrderGoodsExample.or().andIdIn(idList).andStockTypeEqualTo(1);
        List<LitemallOrderGoods> chainOrderGoods = litemallOrderGoodsMapper.selectByExample(chainOrderGoodsExample);
        List<String> rfidsList = new ArrayList<>();
        List<Long> longRfidsList = new ArrayList<>();
        chainOrderGoods.forEach(chain -> {
            if(chain.getStockType()==1){
            String[] rfidList = chain.getRfid().split(",");
            for (int i = 0; i < rfidList.length; i++) {
                rfidsList.add(rfidList[i]);
                longRfidsList.add(Long.parseLong(rfidList[i]));
            }
            }
        });
        if(!rfidsList.isEmpty()&&!longRfidsList.isEmpty()){
        AgedmallLgRfidGoodsCurStatExample goodsCurStatExample=new AgedmallLgRfidGoodsCurStatExample();
        goodsCurStatExample.or().andTypeEqualTo(1).andRfidIn(rfidsList);
        AgedmallLgRfidGoodsCurStat curStat = new AgedmallLgRfidGoodsCurStat();
        AgedmallGoodsEquExample goodsEquExample=new AgedmallGoodsEquExample();
        goodsEquExample.or().andTypeEqualTo(0).andEquIdIn(longRfidsList).andDeletedEqualTo((byte)0);
        AgedmallGoodsEqu goodsEqu=new AgedmallGoodsEqu();
        curStat.setCurStat(0);
        goodsEqu.setState(0);
        agedmallLgRfidGoodsCurStatMapper.updateByExampleSelective(curStat,goodsCurStatExample);
        agedmallGoodsEquMapper.updateByExampleSelective(goodsEqu,goodsEquExample);
            inventoryService.refreshBindingEquAndHomePile(chainOrderGoods.get(0).getStoreId());
        }
    }

    /**
     * 推送用戶消息
     */
    @Override
    public void userNotice() {

    }

    /**
     * @param missionId   missionId
     * @param expressCode 物流单号
     * @param expressName 物流名称
     */
    @Override
    public void thirdLogisEvent(Integer missionId, String expressCode, String expressName, Integer type) throws CheckException {
        logger.debug("第三方物流:missId={},{},{},{}", missionId, type, expressName, expressCode);
        //更新数据
        AgedmallLgMission mission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(mission.getBaseInfoId().longValue());
        Integer stat = LgBaseInfoStatConstant.getNowStat(agedmallLgBaseInfo.getLgType(), type);
        agedmallLgBaseInfo.setLgStat(stat);
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);

        //新增agedmall_lg_receive_order  agedmall_lg_busi_record
        AgedmallLgReceiveOrder receiveOrder = insertReceiveOrder(agedmallLgBaseInfo, null, null, 2, missionId.longValue());
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(mission.getId().longValue(), receiveOrder.getId(), mission.getType(), agedmallLgBaseInfo.getOrderCode(), 1);
        //更改订单商品的状态
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), stat);

        //给第三方物流下单
        logger.debug("开始顺丰下单:missId={},orderCode={}", missionId, agedmallLgBaseInfo.getOrderCode());
        String lgContent = agedmallLgBaseInfo.getLgContent();
        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(lgContent);
        ShunfengCreateOrderBody shunfengCreateOrderBody = new ShunfengCreateOrderBody();
        shunfengCreateOrderBody.initLogisticsData(commonData);
        ShunfengResponseData<ShunfengResposeCreateOrder> createRst = ThirdLogisticShunFengTool.createOrder(shunfengCreateOrderBody);
        if (createRst == null) {
            logger.error("顺丰物流下单失败{},{} null", missionId, agedmallLgBaseInfo.getOrderCode());
            throw new CheckException(ResultCode.LG_SHUNFENG_ERR_CREATE);
        }
        if (!createRst.getCode().equals("0")) {
            logger.error("顺丰物流下单失败{},{},{}", missionId, agedmallLgBaseInfo.getOrderCode(), JacksonUtil.gson.toJson(createRst));
            throw new CheckException(ResultCode.LG_SHUNFENG_ERR_CREATE_ERR);
        }
        String mailNoStr = createRst.getData().stream().map(r -> r.getMailno()).collect(Collectors.joining(","));
        String thirdOrderId = createRst.getData().stream().map(r -> r.getOrderId()).collect(Collectors.joining(","));
        //运单号
        expressCode = mailNoStr;
        //目前仅支持顺丰下单
        expressName = "顺丰";

        //增加第三方物流
        AgedmallLgThirdLogisRecord thirdLogisRecor = new AgedmallLgThirdLogisRecord();
        thirdLogisRecor.setCreatedTime(LocalDateTime.now());
        thirdLogisRecor.setReceiveOrderId(receiveOrder.getId());
        thirdLogisRecor.setOrderCode(agedmallLgBaseInfo.getOrderCode());
        thirdLogisRecor.setThirdOrderCode(expressCode);
        thirdLogisRecor.setThirdOrderId(thirdOrderId);
        thirdLogisRecor.setLgBaseInfoId(agedmallLgBaseInfo.getId());
        thirdLogisRecor.setLgBusiId(agedmallLgBusiRecord.getId());
        thirdLogisRecor.setThirdLogisName(expressName);
        agedmallLgThirdLogisRecordMapper.insertSelective(thirdLogisRecor);
    }

    /**
     * 退货取货完成事件
     *
     * @param missionId
     * @param imgs
     */
    @Override
    public void returnPickupCompletionEvent(Integer missionId, List<String> imgs) {
        //退货取货完成
        goodsRejectedServiceImpl.pickupIsComplete(missionId, imgs);

    }

    /**
     * 换货取货完成事件
     *
     * @param missionId
     * @param imgs
     */
    @Override
    public void exchangeAcquisitionCompletionEvent(Integer missionId, List<String> imgs) {
        goodsChangeServiceImpl.exchangeAndPickupCompleted(missionId, imgs);
    }

    /**
     * 换货配货完成事件
     *
     * @param missionId
     * @param imgs
     */
    @Override
    public void replacementAndDistributionCompletionEvent(Integer missionId, List<String> imgs) {
        goodsChangeServiceImpl.replacementAndDistributionCompleted(missionId, imgs);
    }

    /**
     * 换货送货完成事件
     *
     * @param missionId
     */
    @Override
    public void exchangePickUpAndDeliveryCompleted(Integer missionId) {
        goodsChangeServiceImpl.exchangeGoodsDeliveryCompleted(missionId);
    }


    /**
     * 检查订单物流是否符合基本的业务要求
     *
     * @param bigOrderCode
     * @throws CheckException
     */
    @Override
    public void checkLgBaseOrderStat(String bigOrderCode) throws CheckException {

        LitemallOrder litemallOrder = litemallOrderService.findOrderByOrderCode(bigOrderCode);
        if (litemallOrder == null) {
            throw new CheckException(ResultCode.ORDER_ERROR_NO_EXISTS);
        }

        int orderStatus = litemallOrder.getOrderStatus();

        if (orderStatus == STATUS_CREATE) {
            throw new CheckException(ResultCode.ORDER_ERROR_NO_PAY);
        }

        if (orderStatus == STATUS_CANCEL) {
            throw new CheckException(ResultCode.ORDER_ERROR_CANCEL);
        }

        if (orderStatus == STATUS_AUTO_CANCEL) {
            throw new CheckException(ResultCode.ORDER_ERROR_SYS_CANCEL);
        }

    }

    /**
     * 检查归还订单是否取消
     *
     * @param lgIsOver
     */
    public void checkBackIsCancel(int lgIsOver) throws CheckException {
        if (lgIsOver == LgBaseInfoIsOverEnum.CANCEL.getCode()) {
            throw new CheckException(ResultCode.ORDER_ERROR_LG_RETURN_CANCEL);
        }
    }


}
